/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年11月21日
 */
package com.massyframework.beanskin.runtime.service.serialize;

import java.io.IOException;
import java.util.Objects;

import com.massyframework.beanskin.Module;
import com.massyframework.beanskin.ModuleIdentifier;
import com.massyframework.beanskin.ModuleNotFoundException;
import com.massyframework.beanskin.ModuleRepository;
import com.massyframework.beanskin.SimpleModuleIdentifier;
import com.massyframework.beanskin.service.serialize.PlatformSerializer;


/**
 * 平台级别的序列化器，可支持在massyframework进程之间对DTO进行序列化反序列化.
 * @author huangkh
 *
 */
public final class DefaultPlatformSerializer extends AbstractSerializer
	implements PlatformSerializer{

	private ModuleRepository moduleRepo;
	
	/**
	 * 构造方法
	 * @param {@link ModuleRepository},模块资源库
	 */
	public DefaultPlatformSerializer(ModuleRepository moduleRepo) {
		this.moduleRepo = Objects.requireNonNull(moduleRepo, "\"moduleRepo\" cannot be null.");
	}

	@Override
	public byte[] serial(Object target) throws IOException {
		if (target == null) return new byte[0];
		return this.doSerial(target, true);
	}

	@Override
	public Object deserial(byte[] bytes) throws IOException, ClassNotFoundException {
		if (bytes == null) return null;
		if (bytes.length == 0) return null;
		
		return this.doDeserial(bytes, true);
	}

	@Override
	protected ClassLoader retrieveClassLoader(String identifierString) {
		if (identifierString == null) {
			identifierString = IDENTIFIER_KERNEL;
		}
		
		ModuleIdentifier mi =
				SimpleModuleIdentifier.createModuleIdentifier(identifierString);
		Module<?> module =
				this.moduleRepo.findModuleByIdentifier(mi);
		if (module == null) {
			throw new ModuleNotFoundException(mi);
		}
		return module.getModuleClassLoader();
	}
}
